import qs from 'qs'

/**
 * 样式对象转换成样式字符串, 如下:
 * { marginTop: 1px, 'padding-bottom': 2px } => marginTop: 1px; padding-bottom: 2px;
 */
export const paserStyleStr = (attrs) => {
  let styleStr = ''
  Object.keys(attrs).forEach(attr => {
    styleStr += `${attr}: ${attrs[attr]};`
  })

  return styleStr
}

/**
 * 获取值的类型
 * @param {any} val
 * @returns {string} - [string, number, array, object, null, undefined]
 */
export const typeof2 = (val) => {
  const str = Object.prototype.toString.call(val)
  return str.substring(8, str.length - 1).toLocaleLowerCase()
}

/**
 * 获取 url 参数
 * @param {String} url - https://xxx.com?a=1&b=2
 * @returns { a: 1, b: 2}
 */
export const getUrlParams = url => {
  const index = url.indexOf('?')
  if (index === -1) return {}

  const params = url.slice(index + 1)
  return qs.parse(params)
}

/**
 * 获取参数列表中符合值的标题名
 * @param {array} data
 * @param {string|number|boolean|null} data
 */
export const parseByValue = (data, value) => {
  const i = data.find(el => el.value === value)

  return i ? i.label : value
}

/**
 * 值转换为数字
 * @param {any} str - 被转换的值
 * @param {number} decimal - 转换后保留的位数
 */
export const parseNumber = (str = 0, decimal = 2) => {
  const num = +str

  if (isNaN(num)) return 0

  const x = Math.pow(10, decimal)
  return Math.round(num * x) / x
}

// 单位转换
export function bytesToSize (sizes) {
  let mYsize = sizes
  if (mYsize === 0) return 0 + 'B'
  if (mYsize < 0.1) {
    // 小于0.1KB转换为B
    mYsize = parseFloat((mYsize * 1024).toFixed(2)) + 'B'
  } else if (mYsize > (0.1 * 1024)) {
    // 大于0.1MB转换为MB
    mYsize = parseFloat((mYsize / 1024).toFixed(2)) + 'MB'
  } else if (mYsize > (0.1 * 1024 * 1024)) {
    // 大于0.1GB转换为GB
    mYsize = parseFloat((mYsize / 1024 / 1024).toFixed(2)) + 'GB'
  } else {
    mYsize = mYsize + 'KB'
  }

  return mYsize
}

export const copy = (value) => {
  if (value === undefined) return value

  return JSON.parse(JSON.stringify(value))
}

export const parseAmount = (str) => {
  let result = str

  if (typeof2(str) === 'string') result = str.replace(/¥|积分/ig, '')
  return result
}
